package com.bone.common.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bone.common.exception.BoneException;
import org.springframework.beans.BeanUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;


/**
 * @author :
 * @date : 2020/12/7 9:42
 * Description : 自定义工具类
 */
public class BoneUtils {

    private static final String EMPTY = "";

    private static final String EMPTY_NULL = "null";

    private static final String UNKNOWN = "unknown";

    private static final String X_FORWARDED_FOR = "x-forwarded-for";

    private static final String PROXY_CLIENT_IP = "Proxy-Client-IP";

    private static final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";

    /**
     * 定义迭代次数为1000次
     */
    private static final int ITERATION_COUNT = 1000;

    private static final String CHART_SET = "utf-8";

    /**
     * 定义使用的算法为:PBEWITHMD5andDES算法 	加密算法
     */
    private static final String ALGORITHM = "PBEWithMD5AndDES";

    private static final String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 判断某个实体类是否为空
     *
     * @param object 实体信息
     * @return true:false
     */
    public static boolean isEmpty(Object object) {
        if (object == null) {
            return (true);
        }
        if (EMPTY.equals(object)) {
            return (true);
        }
        return EMPTY_NULL.equals(object);
    }

    /**
     * 判断某个实体类是否为不为空
     *
     * @param object 实体信息
     * @return true:false
     */
    public static boolean isNotEmpty(Object object) {
        return object != null && !object.equals(EMPTY) && !object.equals(EMPTY_NULL);
    }

    /**
     * 判断某个字符串为空
     *
     * @param str 字符串
     * @return true:false
     */
    public static boolean isEmpty(String str) {
        return str == null || str.equals(EMPTY);
    }


    /**
     * 判断某个字符串不为空
     *
     * @param str 字符串
     * @return true:false
     */
    public static boolean isNotEmpty(String str) {
        return str != null && !str.equals(EMPTY);
    }


    /**
     * 判断 list 是否为空
     *
     * @param list 集合
     * @return true or false
     * list == null		: true
     * list.size() == 0	: true
     */
    public static boolean listIsEmpty(Collection list) {
        return (list == null || list.size() == 0);
    }

    /**
     * 判断 list 是否不为空
     *
     * @param list 集合
     * @return true or false
     * list == null		: false
     * list.size() == 0	: false
     */
    public static boolean listIsNotEmpty(Collection list) {
        return !listIsEmpty(list);
    }


    /**
     * 将实体类F 转换成实体类T
     *
     * @param entity     实体类F
     * @param modelClass 实体类T的class
     * @return 实体类T
     */
    public static <F, T> T entityToModel(F entity, Class<T> modelClass) {
        T model;
        if (isEmpty(entity) || isEmpty(modelClass)) {
            return null;
        }
        try {
            // 通过反射获取对象
            model = modelClass.newInstance();
        } catch (InstantiationException e) {
            throw new BoneException("entityToModel : 实例化异常", e);
        } catch (IllegalAccessException e) {
            throw new BoneException("entityToModel : 安全权限异常", e);
        }
        // 转换
        BeanUtils.copyProperties(entity, model);
        return model;
    }

    /**
     * 将实体类F类型的集合 转换成实体类T类型的集合
     *
     * @param fromList 实体类F类型的集合
     * @param tClass   实体类T的class
     * @return 实体类T类型的集合
     */
    public static <F, T> List<T> entityListToModelList(List<F> fromList, Class<T> tClass) {
        if (listIsEmpty(fromList) || isEmpty(tClass)) {
            return null;
        }
        // 通过JAVA8 流的形式进行转换
        return fromList.stream().map(i -> entityToModel(i, tClass)).collect(Collectors.toList());
    }

    /**
     * 将实体类F类型的分页对象 转换成实体类T类型的分页对象
     *
     * @param iPage  实体类F类型的分页对象
     * @param tClass 实体类T的class
     * @return 实体类T类型的分页对象
     */
    public static <F, T> IPage<T> entityPageToModelPage(IPage<F> iPage, Class<T> tClass) {
        if (iPage == null || isEmpty(tClass)) {
            return null;
        }
        IPage<T> tPage = new Page<>();
        // 首先转换对象
        BeanUtils.copyProperties(iPage, tPage);
        if (listIsEmpty(iPage.getRecords())) {
            // 如果数据为空则直接返回
            return tPage;
        }
        // 再转换分页对象内数据的类型
        tPage.setRecords(entityListToModelList(iPage.getRecords(), tClass));
        return tPage;
    }

    /**
     * 获取请求的IP地址
     *
     * @param request 请求
     * @return IP地址
     */
    public static String getIpAddressByRequest(HttpServletRequest request) {
        String ip = request.getHeader(X_FORWARDED_FOR);
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(PROXY_CLIENT_IP);
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(WL_PROXY_CLIENT_IP);
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    /**
     * 生成随机8位盐值
     */
    public static String getRandomSalt() {
        Random random = new Random();
        char[] keys = new char[8];
        for (int i = 0; i < keys.length; i++) {
            // 取得大写还是小写
            int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
            keys[i] = (char) (choice + random.nextInt(26));
        }
        return new String(keys);
    }


    /**
     * 加密明文字符串
     *
     * @param plaintext 待加密的明文字符串
     * @param password  生成密钥时所使用的密码
     * @param salt      盐值
     * @return 加密后的密文字符串
     */
    public static String encrypt(String plaintext, String password, String salt) {

        Key key = getPBEKey(password);
        byte[] encipheredData = null;
        PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATION_COUNT);
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);

            cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
            //update-begin-author:sccott date:20180815 for:中文作为用户名时，加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7
            encipheredData = cipher.doFinal(plaintext.getBytes(CHART_SET));
            //update-end-author:sccott date:20180815 for:中文作为用户名时，加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7
        } catch (Exception e) {
            throw new BoneException(e);
        }
        return bytesToHexString(encipheredData);
    }

    /**
     * 解密密文字符串
     *
     * @param cipherText 待解密的密文字符串
     * @param password   生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致)
     * @param salt       盐值(如需解密,该参数需要与加密时使用的一致)
     * @return 解密后的明文字符串
     */
    public static String decrypt(String cipherText, String password, String salt) {

        Key key = getPBEKey(password);
        byte[] passDec;
        PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATION_COUNT);
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);

            cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);

            passDec = cipher.doFinal(hexStringToBytes(cipherText));
        } catch (Exception e) {
            // TODO: handle exception
            throw new BoneException(e);
        }
        return new String(passDec);
    }

    /**
     * 根据PBE密码生成一把密钥
     *
     * @param password 生成密钥时所使用的密码
     * @return Key PBE算法密钥
     */
    private static Key getPBEKey(String password) {
        // 实例化使用的算法
        SecretKeyFactory keyFactory;
        SecretKey secretKey = null;
        try {
            keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            // 设置PBE密钥参数
            PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
            // 生成密钥
            secretKey = keyFactory.generateSecret(keySpec);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return secretKey;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param src 字节数组
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 将十六进制字符串转换为字节数组
     *
     * @param hexString 十六进制字符串
     */
    private static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals(EMPTY)) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    public static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }


}
